package com.dst.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.dst.utli.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
public class adminFilter implements GlobalFilter, Ordered {
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String uri = exchange.getRequest().getURI().toString();
    if(uri.indexOf("/user-test/")>-1){
      return chain.filter(exchange);
    }
    if(uri.indexOf("/admin/")>-1){
      List<String> authorization = exchange.getRequest().getHeaders().get("authorization");
      if(authorization!=null&authorization.size()>0){
        String token = authorization.get(0);
        try {
          DecodedJWT verify = JwtUtils.verify(token);
          String role = verify.getClaim("role").asString();
          if("1".equals(role)){
            return chain.filter(exchange);
          }
        } catch (Exception e) {
          exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
          return exchange.getResponse().setComplete();
        }
      }
      }else {
      return chain.filter(exchange);
    }
    exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
    return exchange.getResponse().setComplete();
  }

  @Override
  public int getOrder() {
    return 1 ;
  }
}
